package com.example.networkasking;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

/**
 *以登陆为例，此方法可以用在所有需要使用到网络连接的地方
 * 由于我们的发送数据是直接用字符串发送，需要观察后端的接受类型是什么，需要与之匹配。
 */
public class MainActivity extends AppCompatActivity {

    private String Url = "http://";//输入需要访问的Url

    public String ID;//账号
    public String PWD;//密码


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Login(ID,PWD);//调用登陆函数
    }

    /**
     * 登陆函数
     * @param id  账号
     * @param pwd  密码
     */
    public void Login(String id,String pwd) {
        new Thread() {
            @Override
            public void run() {
                try {
                    String ticket = loginconnection(id,pwd);
                    JSONObject object = new JSONObject(ticket);

                    int code = object.optInt("code");
                    final String msg = object.optString("msg");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    /**
     * 网络连接
     * @param username
     * @param pwd
     * @return
     */
    private String loginconnection(String username,String pwd){
        try {
            URL url = new URL(Url);
            HttpURLConnection cn = (HttpURLConnection) url.openConnection();
            cn.setRequestMethod("POST");
            cn.setDoOutput(true);
            cn.setUseCaches(false);
            //发送数据位置
            String str = "username=" + URLEncoder.encode(username, "utf-8")
                    + "&password=" + URLEncoder.encode(pwd, "utf-8");
            OutputStream outputStream = cn.getOutputStream();
            outputStream.write(str.getBytes());
            outputStream.flush();
            if (cn.getResponseCode()==200){
                InputStream inputStream = cn.getInputStream();
                String s = stream2String(inputStream);
                return s;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 译码函数
     * 功能：为了将后端返回的值进行解析
     * @param is
     * @return
     */
    private String stream2String(InputStream is){
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        StringBuffer sb = new StringBuffer();
        String line;
        try {
            while ((line=br.readLine()) != null) {
                sb.append(line);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return sb.toString();
    }
}